import * as turf from "@turf/turf";

function MapCore(container, MapOptions) {
  this.provider = "providertmp"; //地图供应商
  this.key = "keytmp"; //地图key
  if (MapOptions == undefined) {
    MapOptions = {};
    MapOptions.enableMapClick = false;
  }
  if (MapOptions != undefined && MapOptions.enableMapClick == undefined) {
    MapOptions.enableMapClick = false;
  }
  MapOptions.viewMode = "3D"; //开启3D视图,默认为关闭
  this.map = new AMap.Map(container, MapOptions); //高德地图对象
  this.mapDivId = container;
  this.zoom; //缩放级别
  this.centerPoint; //中心点
  this.meMapValue = {}; //存放方法值  通过getMeMapValue(方法名称获得)  removeMeMapValue(方法名称进行删除)
  this.trafficLayer; //卫星/普通图层
  this.polyEditor;
  this.mapType = "gaode";
  this.prejoctUrl = "optimoveAppAddress";
  this.nginxUrl = "gateWayAddress";
  this.nginxImage = "gateWayAddressnbcbimages";
  this.uploadImageUrl = "_UPLOAD_IMAGE_URL";
  this.cityRect = {
    minLng: 9999,
    maxLng: 0,
    minLat: 9999,
    maxLat: 0,
  };
  this.heatmap = {}; //热力图
  this._HeatmapLoaded = {
    isHeatmapLoaded: false
  };
  this._RangingToolLoaded = {
    isRangingToolLoaded: false
  };
  this.ruler = {};
  this._placeSearch = {}; //poi检索工具，默认只有一个
  this.mapTracks = [];
  this.cluster = []; //高德聚合点对象集合
  this.walking = {};
  this.driving = {};
  this.transfer = {};
  this.resultJson = []; // 存放画图返回的json数组
  this.overlays = [];
  this.selectMap = null
}

/**
 * 地图类的成员方法
 */
MapCore.prototype = {
  constructor: MapCore, //地图构造方法
  enableZoom: function (flag) {
    //启用缩放
    this.map.setStatus({
      zoomEnable: flag
    });
  },
  setCenterAndZoom: function (centerPoint, zoom) {
    //定位
    if (typeof centerPoint != "string") {
      this.centerPoint = centerPoint;
      this.zoom = zoom;
      this.map.setZoomAndCenter(this.zoom, this.centerPoint);
    }
  },
  addControls: function () {
    this.map.viewMode = "3D";
    map.addControl(
      new AMap.ControlBar({
        showZoomBar: false,
        showControlButton: true,
        position: {
          right: "10px",
          top: "10px",
        },
      })
    );
  },
  goPan: function (point) {
    //将地图的中心点更改为给定的点
    this.map.panTo([point.lon, point.lat]);
  },
  getCenter: function () {
    return this.map.getCenter(); //获取地图当前中心点
  },
  setCenter: function (Point) {
    //设置中心点
    this.map.setCenter(Point);
  },
  addMarker: function (marker) {
    //添加标志
    marker.setMap(this.map);
  },
  getZoom: function () {
    //返回当前缩放级别
    return this.map.getZoom();
  },
  setZoom: function (zoomNum) {
    //重新设置地图级别
    this.map.setZoom(zoomNum);
  },
  setMarkerIcon: function (marker, vicon) {
    //添加标记的图标
    if (marker != undefined && vicon != undefined) {
      marker.setIcon(vicon);
    }
  },
  setMapStyle: function (style) {
    let styleName = "amap://styles/";
    styleName = styleName + style.style;
    this.map.setMapStyle(styleName);
  },
  addDrawingManager: function (fn, style) {
    let jsonObj = {};
    if (typeof fn === "function") {
      jsonObj.drawingFun = fn;
    } else {
      if (fn) {
        jsonObj = fn;
      }
    }
    if (!style) {
      style = {};
    }

    const key = "addDrawingManager";
    const _this = this;
    let mouseTool = null;
    _this.map.plugin(["AMap.MouseTool"], function () {
      mouseTool = new AMap.MouseTool(_this.map);
      // 删除覆盖物
      document.getElementById('clearAllGrid').addEventListener('click', function () {
        console.log('this.selectMap', this.selectMap)
        if (this.selectMap) _this.map.remove(this.selectMap)
        _this.selectMap = null
      })
      document.getElementById('editGrid').addEventListener('click', () => {
        _this.polyEditor.open()
      })
      let tempDrawListener;
      // 拖动地图
      AMap.event.addDomListener(
        document.getElementById("move"),
        "click",
        function () {
          document.getElementById("move").classList.add('move')
          document.getElementById("polygon").classList.remove('move')
          document.getElementById('polyline').classList.remove('move')
          _this.map.setDefaultCursor('pointer');
          if (tempDrawListener) {
            mouseTool.close();
            AMap.event.removeListener(tempDrawListener)
          }
        },
        false
      );
      AMap.event.addDomListener(
        document.getElementById("polygon"),
        "click",
        function () {
          if (tempDrawListener) {
            mouseTool.close()
            AMap.event.removeListener(tempDrawListener)
          }
          document.getElementById('move').classList.remove('move')
          document.getElementById("polygon").classList.add('move')
          document.getElementById('polyline').classList.remove('move')
          mouseTool.polygon();
          _this.map.setDefaultCursor('crosshair')
          tempDrawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
            this.selectMap = e.obj
            addDraw("polygon", e.obj);
            _this.map.plugin(["AMap.PolyEditor"], function () {
              _this.polyEditor = new AMap.PolyEditor(_this.map, e.obj);
              addEdit("polygon", polyEditor, e.obj);
            });
          })
        },
        false
      );
      // 画线
      AMap.event.addDomListener(
        document.getElementById("polyline"),
        "click",
        function () {
          if (tempDrawListener) {
            mouseTool.close();
            mouseTool.off(tempDrawListener);
          }
          mouseTool.polyline();
          document.getElementById('move').classList.remove('move')
          document.getElementById("polygon").classList.remove('move')
          document.getElementById('polyline').classList.add('move')
          tempDrawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
            addDraw("polyline", e.obj);
            _this.map.plugin(['AMap.PolyEditor'], function () {
              _this.polyEditor = new AMap.PolyEditor(_this.map, e.obj);
              addEdit("polyline", polyEditor, e.obj);
            });
          }, false)
        },
        false
      );

      // 绘制添加方法
      function addDraw(type, plane) {
        document.getElementById("move").click();
        const handle = document.getElementById("handle")
        handle.style.display = 'inline-block'
        if (type == "circle") {
          _this.map.remove(plane);
          const center = [
            Number(plane.getCenter().lng),
            Number(plane.getCenter().lat),
          ];
          const radius = plane.getRadius() / 1000;
          if (radius == 0) {
            return;
          }
          const options = {
            steps: 50,
            units: "kilometers",
            properties: {
              foo: "bar"
            },
          };
          const circle = turf.circle(center, radius, options);
          const jsonPoint = circle.geometry.coordinates[0];
          const polygon = new AMap.Polygon({
            path: jsonPoint,
            strokeColor: "#00ae66",
            strokeOpacity: 1,
            fillColor: "#00ae66",
            fillOpacity: 0.3,
            enableClicking: false,
          });
          _this.addOverlay(polygon);
          _this.map.plugin(["AMap.PolyEditor"], function () {
            const polyEditor = new AMap.PolyEditor(_this.map, polygon);
            addEdit("polygon", polyEditor, polygon);
          });
          _this.overlays.push(polygon);
          const json = {
            type: "polygon",
            point: polygon.getPath().toString(),
            provider: "gaode",
          };
          _this.resultJson.push(json);
          if (jsonObj.drawingFun) {
            jsonObj.drawingFun(_this.resultJson, _this.overlays);
          }
          _this.setMeMapValue(key, json);
        } else {
          // 面、线、矩形
          _this.overlays.push(plane);
          const str = {
            type: type,
            point: plane.getPath().toString(),
            provider: "gaode",
          };
          _this.resultJson.push(str);
          if (jsonObj.drawingFun) {
            jsonObj.drawingFun(_this.resultJson, _this.overlays);
          }
          _this.setMeMapValue(key, str);
        }
      }
      // 添加图形编辑菜单
      function addEdit(type, polyEditor, plane) {
        const menu = new AMap.ContextMenu();
        const txtMenuItem = [{
            text: "编辑",
            callback: function () {
              // console.log(plane);
              polyEditor.open();
            },
          },
          {
            text: "关闭",
            callback: function () {
              // console.log(plane);
              polyEditor.close();
              addDraw(type, plane);
            },
          },
        ];

        for (let i = 0; i < txtMenuItem.length; i++) {
          menu.addItem(
            txtMenuItem[i].text,
            txtMenuItem[i].callback || function () {},
            i
          );
        }
        plane.on("rightclick", function (e) {
          menu.open(_this.map, e.lnglat);
        });
      }
    });
  },
  /**
   * 添加覆盖物
   * @param data
   */
  addOverlay: function (data) {
    //添加覆盖物
    this.map.add(data);
  },
  addScaleControl: function () {
    //设置比例尺
    const myMap = this.map;
    myMap.plugin(["AMap.Scale"], function () {
      const scale = new AMap.Scale();
      myMap.addControl(scale);
      scale.show();
    });
  },
  /**
   * 设置方法存放值
   * @param 方法名称
   * @return
   */
  setMeMapValue: function (key, value) {
    this.meMapValue[key] = value;
  },
  /**
   * 移除覆盖物
   */
  clearOverlays: function () {
    //移除覆盖物
    this.map.clearMap();
    // this.removeAllClusterers();
    // this.removeHeatMap();
    // this.removeAllTracks();
  },
  /**
   * 删除Marker点
   * @return
   */
  removeOverlay: function (overlay) {
    let objs = overlay;
    if (!(objs instanceof Array)) {
      objs = [overlay];
    }
    this.map.remove(objs);
  },
  // 清除点聚合
  removeAllClusterers: function () {
    for (let i = 0; i < this.cluster.length; i++) {
      this.cluster[i].clearMarkers();
    }
    this.cluster.splice(0, this.cluster.length);
  },
  //清除热力图
  removeHeatMap: function () {
    if (Object.keys(this.heatmap).length !== 0) {
      // 清除热力图图层
      // $("#_amap_heatmap_div_").remove();
      this.heatmap = {};
    }
  },
  removeAllTracks: function () { //删除所有轨迹对象
    for (let i = 0; i < this.mapTracks.length; i++) {
      if (JSON.stringify(this.mapTracks[i].getPathSimplifier()) != '{}') {
        this.mapTracks[i].getPathSimplifier().setData([]);
      }
    }
  },
  addMapType: function (num = 0) {
    // const myMap = this.map;
    this.trafficLayer = new AMap.TileLayer.Satellite()
  },
  // 地图图层切换
  addMapTypeControl: function () {
    this.map.add(this.trafficLayer)
  },
  removeMapTypeControl: function () {
    if (this.trafficLayer) {
      this.map.remove(this.trafficLayer)
    }
  },
  removePolygon: function () {

  }
};
/**
 * 地图子类
 */
MapCore.Point = function (arr) {
  //点类
  return new AMap.LngLat(arr[0], arr[1]);
};
MapCore.MyLabel = function (thml, opt) {
  const obj = {
    text: thml,
    position: opt.position,
  };
  return new AMap.Text(obj);
};

export default MapCore;